import 'package:e_reception_flutter/constants/constant.dart';
import 'package:e_reception_flutter/media_library/media_library_index/media_library_index_page.dart';
import 'package:e_reception_flutter/singleton/amap_repository/amap_repository.dart';
import 'package:e_reception_flutter/singleton/theme_repository/color_constants.dart';
import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/singleton/user_repository/user_repository.dart';
import 'package:e_reception_flutter/ui/ai_poster/ai_poster_index_page.dart';
import 'package:e_reception_flutter/ui/index/index_page.dart';
import 'package:e_reception_flutter/ui/mypage/mypage.dart';
import 'package:e_reception_flutter/utils/app_monitoring_class.dart';
import 'package:e_reception_flutter/utils/router_utils.dart';
import 'package:e_reception_flutter/vg_widgets/vg_bottom_navigation_bar/vg_bottom_navigation_bar.dart';
import 'package:e_reception_flutter/vg_widgets/vg_bottom_navigation_bar/vg_bottom_navigation_bar_item.dart';
import 'package:e_reception_flutter/vg_widgets/vg_upgrade/vg_net_delegate.dart';
import 'package:e_reception_flutter/vg_widgets/vg_upgrade/vg_windows_delegate.dart';
import 'package:flutter/material.dart';
import 'package:upgrade_flutter/upgrade_flutter.dart';
import 'package:vg_base/vg_arch_lib.dart';
import 'package:vg_base/vg_evnet_bus_lib.dart';
import 'package:vg_base/vg_sp_lib.dart';
import 'package:vg_flutter_base_moudle/vg_moudle_widget_lib.dart';

import '../app_main.dart';
import 'even/index_refresh_even.dart';
import 'widgets/index_admin_upload_face_dialog.dart';

/// 首页导航页
///
/// @author: zengxiangxi
/// @createTime: 1/11/21 5:32 PM
/// @specialDemand:
class IndexNavPage extends StatefulWidget {
  ///路由名称
  static const String ROUTER = "IndexNavPage";

  @override
  _IndexNavPageState createState() => _IndexNavPageState();

  ///跳转方法
  static Future<dynamic> navigatorPush(BuildContext context) {
    return RouterUtils.routeForFutureResult(
      context,
      IndexNavPage(),
      routeName: IndexNavPage.ROUTER,
    );
  }
}

class _IndexNavPageState extends BaseState<IndexNavPage> with  WidgetsBindingObserver {
  static const DEFAULT_PAGE_POSITION = 0;

  int _currentPage = DEFAULT_PAGE_POSITION;

  ///控制器
  PreloadPageController _pageController;

  List<Widget> _pageList;

  ///底部项
  final List<VgBottomNavigationBarItem> bottomNavItems = [
    VgBottomNavigationBarItem(
      customUnselectWidget: _NavigationItemWidget(
        iconAsset: "images/nav_terminal_selected_ico.png",
        text: "终端管理",
        iconColor: ThemeRepository.getInstance().getTextMainColor_D0E0F7(),
        textColor: ThemeRepository.getInstance().getTextMainColor_D0E0F7(),
        assetOpacity: 1,
      ),
      customSelectedWidget: _NavigationItemWidget(
        iconAsset: "images/nav_terminal_selected_ico.png",
        text: "终端管理",
        textColor: ThemeRepository.getInstance().getTextMainColor_D0E0F7(),
      ),
    ),
    VgBottomNavigationBarItem(
        customUnselectWidget: _NavigationItemWidget(
          iconAsset: "images/nav_library_selected_ico.png",
          text: "播放资料库",
          iconColor: ThemeRepository.getInstance().getTextMainColor_D0E0F7(),
          textColor: ThemeRepository.getInstance().getTextMainColor_D0E0F7(),
          assetOpacity: 1,
        ),
        customSelectedWidget: _NavigationItemWidget(
          iconAsset: "images/nav_library_selected_ico.png",
          text: "播放资料库",
          textColor: ThemeRepository.getInstance().getTextMainColor_D0E0F7(),
        )
    ),
    VgBottomNavigationBarItem(
        customUnselectWidget: _NavigationItemWidget(
          iconAsset: "images/nav_ai_poster_un_selected_ico.png",
          text: "制作中心",
          textColor: ThemeRepository.getInstance().getTextMainColor_D0E0F7(),
          assetOpacity: 1,
        ),
        customSelectedWidget: _NavigationItemWidget(
          iconAsset: "images/nav_ai_poster_selected_ico.png",
          text: "制作中心",
          textColor: ThemeRepository.getInstance().getTextMainColor_D0E0F7(),
        )
    ),
    VgBottomNavigationBarItem(
        customUnselectWidget: _NavigationItemWidget(
          iconAsset: "images/nav_my_selected_ico.png",
          text: "我的",
          iconColor: ThemeRepository.getInstance().getTextMainColor_D0E0F7(),
          textColor: ThemeRepository.getInstance().getTextMainColor_D0E0F7(),
          assetOpacity: 1,
        ),
        customSelectedWidget: _NavigationItemWidget(
          iconAsset: "images/nav_my_selected_ico.png",
          text: "我的",
          textColor: ThemeRepository.getInstance().getTextMainColor_D0E0F7(),
        )
    ),
  ];

  @override
  void initState() {
    super.initState();
    _pageController = PreloadPageController(
        initialPage: DEFAULT_PAGE_POSITION, keepPage: true);
    _pageList = [IndexPage(), MediaLibraryIndexPage(), AiPosterIndexPage(), Mypage()];
    //gzz先注释
    // Future.delayed(Duration(milliseconds: 1000), () {
    //   IndexAdminUploadFaceDialog.navigatorPushDialog(AppMain.context);
    // });
    showUploadFaceDialog();
    ///加载高德定位插件
    AmapRepository.getInstance().init();

  }

  @override
  void dispose() {
    _pageController?.dispose();
    super.dispose();
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    switch (state) {
      case AppLifecycleState.inactive: // 处于这种状态的应用程序应该假设它们可能在任何时候暂停。
        break;
      case AppLifecycleState.resumed: //从后台切换前台，界面可见
      // showUploadFaceDialog();

        break;
      case AppLifecycleState.paused: // 界面不可见，后台
        break;
      case AppLifecycleState.detached: // APP结束时调用
        break;
    }
  }

  @override
  Widget build(BuildContext context) {

    return Scaffold(
      resizeToAvoidBottomInset: false,
      resizeToAvoidBottomPadding: false,
      body: _toStackWidget(),
    );
  }

  Widget _toStackWidget() {
    return Stack(
      children: <Widget>[
        _toPagesWidget(),
        Align(
          alignment: Alignment.bottomCenter,
          child: _toNavigatorBarWidget(),
        )
      ],
    );
  }

  Widget _toNavigatorBarWidget() {
    return Theme(
        data: ThemeData(
            highlightColor: Colors.transparent,
            splashColor: Colors.transparent),
        child: _toBottomNavigationBarWidget());
  }

  Widget _toPagesWidget() {
    return PreloadPageView(
      controller: _pageController,
      preloadPagesCount: _pageList?.length ?? 0,
      physics: NeverScrollableScrollPhysics(),
      children: _pageList,
    );
  }

  Widget _toBottomNavigationBarWidget() {
    return VgBottomNavigationBar(
      backgroundColor: ColorConstants.NAV_COLOR,
      elevation: 15,
      selectedLabelStyle: TextStyle(
        // color: ThemeRepository.getInstance().getBgOrSplitColor_191E31(),
        fontSize: 10,
      ),
      unselectedLabelStyle: TextStyle(fontSize: 10),
      items: bottomNavItems,
      currentIndex: _currentPage,
      type: VgBottomNavigationBarType.fixed,
      onTap: (index) {
        _changePage(index);
        //点击
        if (index == 0) {
          VgEventBus.global.send(IndexRefreshEven());
        }
        if (index == 1) {
          VgEventBus.global.send(MonitoringMediaLibraryIndexClass());
        }
        if (index == 2) {
          VgEventBus.global.send(MonitoringAiPosterIndexClass());
        }
        if (index == 3) {
          VgEventBus.global.send(SubmitProposalInterfaceEventMonitor());
        }
      },
    );
  }

  ///更新页面
  _changePage(int index) {
    if (index == null || index < 0) {
      return;
    }
    _pageController?.jumpToPage(index);
    _currentPage = index;
    setState(() {});
  }

  void showUploadFaceDialog() {
    SharePreferenceUtil.getStringList(KEY_SHOW_HOMEPAGE_DIALOG_FLG)
        .then((List<String> value) {
      List<String> phones = value??[];
      if (phones.contains(UserRepository.getInstance().getCacheKeySuffix())) {
        Future.delayed(Duration(milliseconds: 1000), () {
          if(UserRepository.getInstance().userData.companyInfo.enableFaceRecognition!="00" || !UserRepository.getInstance().userData.companyInfo.isShowFaceRecognition())return;
          IndexAdminUploadFaceDialog.navigatorPushDialog(AppMain.context);
        });
      } else {
        phones.add(UserRepository.getInstance().getCacheKeySuffix());
        SharePreferenceUtil.putStringList(KEY_SHOW_HOMEPAGE_DIALOG_FLG, phones);
      }
    });
  }
}

class _NavigationItemWidget extends StatelessWidget {
  final String iconAsset;
  final String text;
  final Color textColor;
  final double assetOpacity;
  final Color iconColor;

  final int redNumber;

  const _NavigationItemWidget(
      {Key key,
        this.iconAsset,
        this.text,
        this.textColor,
        this.redNumber,
        this.assetOpacity,
        this.iconColor})
      : assert(iconAsset != null && iconAsset != ""),
        assert(textColor != null),
        assert(text != null && text != ""),
        super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      height: NAV_HEIGHT,
      alignment: Alignment.center,
      child: Stack(
        overflow: Overflow.visible,
        children: [
          Column(
            crossAxisAlignment: CrossAxisAlignment.center,
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            mainAxisSize: MainAxisSize.min,
            children: <Widget>[
              Container(
                width: 26,
                height: 26,
                alignment: Alignment.center,
                child: AnimatedOpacity(
                  duration: DEFAULT_ANIM_DURATION,
                  opacity: assetOpacity ?? 1,
                  child: Image.asset(
                    iconAsset ?? "",
                    width: 26,
                    color: iconColor,
                    gaplessPlayback: true,
                  ),
                ),
              ),
              SizedBox(
                height: 1,
              ),
              AnimatedDefaultTextStyle(
                duration: DEFAULT_ANIM_DURATION,
                style: TextStyle(color: textColor, fontSize: 10),
                child: Text(
                  text ?? "",
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                ),
              )
            ],
          ),
          Positioned(
              top: -4,
              left: 18,
              child: Offstage(
                offstage: redNumber == null || redNumber <= 0,
                child: Container(
                  height: 20,
                  constraints: BoxConstraints(minWidth: 20),
                  decoration: BoxDecoration(
                      color: Color(0xffFF455E),
                      borderRadius: BorderRadius.circular(10)),
                  padding: const EdgeInsets.symmetric(horizontal: 3),
                  child: Center(
                    child: Text(
                      "${redNumber ?? 0}",
                      style: TextStyle(
                          color: Colors.white, fontSize: 12, height: 1.3),
                    ),
                  ),
                ),
              ))
        ],
      ),
    );
  }

}
